<?php
/**
 * Created by PhpStorm.
 * User: yaoihu
 * Date: 2019/4/22
 * Time: 20:21
 */

namespace Develop\Models;

use App\Models\System\CurrencyModel as BaseCurrencyModel;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class CurrencyModel extends BaseCurrencyModel
{
    const WALLET_TABLE = 'users_wallet';
    public function addCurrency(CurrencyModel $currency,Request $request)
    {
        $currency->name = $request->post('name');
        $currency->title = $request->post('title');
        $currency->price = $request->post('price');
        $currency->status = $request->post('status',1);
        if($currency->save()){
            return $this->createField( $currency->name);
        }
        return false;

    }

    public function editCurrency(Request $request, $id)
    {
        $currency = self::find($id);
        if(!$currency){
            $this->errorMsg = '删除币种不存在';
            return false;
        }
        $name = $currency->name;
        $new_name = $request->post('name');
        $currency->name = $new_name;
        $currency->title = $request->post('title');
        $currency->price = $request->post('price');
        $currency->status = $request->post('status',1);
        if($currency->save()){

            return $this->renameField($name,$new_name);
        }

        return false;
    }

    public function deleteCurrency($id)
    {
        $currency = self::find($id);
        if(!$currency){
            $this->errorMsg = '删除币种不存在';
            return false;
        }
        $name = $currency->name;
        if($currency->delete()){
            return $this->dropField($name);
        }
        return false;
    }

    public function createField($name)
    {
        if(!Schema::hasColumn(self::WALLET_TABLE,$name)){
            Schema::table(self::WALLET_TABLE,function (Blueprint $table) use($name){
                $scale = env('SYS_SCALE',2);
                $table->decimal($name,10+$scale,$scale)->default(0)->after('member_id');
            });
        }
        return true;
    }

    private function renameField($new_name, $old_name)
    {
        if(($old_name==$new_name&&Schema::hasColumn(self::WALLET_TABLE,$old_name))) {
            return true;
        }

        if($old_name==$new_name){
            return $this->createField($new_name);
        }

        $this->dropField($old_name);
        $this->createField($new_name);
        return true;
    }

    private function dropField($name)
    {
        if(Schema::hasColumn('users_wallet',$name)){
            Schema::table('users_wallet',function (Blueprint $table) use($name){
                $table->dropColumn($name);
            });
        }
        return true;
    }

}